<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-7-26
 * Time: 下午1:35
 */

namespace console\controllers;


use abhimanyu\systemInfo\SystemInfo;
use common\components\tools\FileHelper;
use common\components\tools\Security;
use common\config\Env;
use common\members\wodrow\components\jd_area\JdArea;
use common\members\wodrow\tools\File;
use common\members\wodrow\tools\Model;
use common\models\db\Area;
use common\models\db\Docu;
use common\models\db\DocuCommentReply;
use common\models\db\QueneJob;
use common\models\db\Smms;
use common\models\db\TestTt;
use common\models\db\User;
use common\models\db\UserOperateLog;
use common\models\file_data\FontAwesomeIcons;
use console\members\wodrow\swoole_test\ProxyTcpServer;
use console\members\wodrow\reverse_proxy\Client;
use console\members\wodrow\reverse_proxy\OuterNet;
use console\members\wodrow\reverse_proxy\Server;
use console\members\wodrow\swoolewschat\ChatServer;
use console\members\wodrow\WebProxyServer;
use Curl\Curl;
use Symfony\Component\Finder\Finder;
use yii\console\Controller;

class JobController extends Controller
{
    /**
     * php yii job/test | php yii_dev job/test
     * 测试
     * @throws
     */
    public function actionTest()
    {
        var_dump(\Yii::$app->user);
        exit;
        $file_url = 'https://i.loli.net/2018/10/31/5bd94c2946e78.png';
        $file_path = File::downloadTmpFileFromUrl($file_url);
        $base64 = File::fileToBase64($file_path);
        $base64 = File::removeDataHeaderForBase64($base64);
        var_dump($base64);
    }

    /**
     * 删除任务队列锁
     * php yii job/reset-quene-job-lock
     */
    public function actionResetQueneJobLock()
    {
        $key = Env::$quene_job_lock_key;
        $status = \Yii::$app->cache->set($key, QueneJob::STATUS_DONE);
        var_dump($status);
    }

    /**
     * 初始化所有任务队列
     * php yii job/set-all-quene-job-ready
     */
    public function actionSetAllQueneJobReady()
    {
        $key = Env::$quene_job_lock_key;
        $lock_status = \Yii::$app->cache->get($key);
        if ($lock_status == QueneJob::STATUS_DOING){
            var_dump("job is doing");
            exit;
        }
        $x = QueneJob::updateAll(['status' => QueneJob::STATUS_READY]);
        var_dump($x);
    }

    /**
     * 执行队列任务
     * php yii job/do-quene-job
     * @throws \yii\base\Exception
     */
    public function actionDoQueneJob()
    {
        $key = Env::$quene_job_lock_key;
        $lock_status = \Yii::$app->cache->get($key);
        if ($lock_status == QueneJob::STATUS_DOING){
            var_dump("job is doing");exit;
        }else{
            if(QueneJob::find()->where(['status' => QueneJob::STATUS_DOING])->all()){
                var_dump("job is locked");exit;
            }
            \Yii::$app->cache->set($key, QueneJob::STATUS_DOING, 86400*30);
        }
        $q_jobs = QueneJob::find()->where(['status' => QueneJob::STATUS_READY])->all();
        foreach ($q_jobs as $k => $v){
            $v->status = QueneJob::STATUS_DOING;
            if (!$v->save()){
                var_dump(Model::getModelError($v));
            }
            $quene_job_error = \Yii::getAlias("@runtime/logs/quene_job_error.log");
            $descriptorspec = array(
                0 => array("pipe", "r"),  // 标准输入，子进程从此管道中读取数据
                1 => array("pipe", "w"),  // 标准输出，子进程向此管道中写入数据
                2 => array("file", $quene_job_error, "a"), // 标准错误，写入到一个文件
            );
            if (!is_dir(dirname($quene_job_error))){
                \yii\helpers\FileHelper::createDirectory(dirname($quene_job_error), 0777);
            }
            $cwd = \Yii::getAlias('@project_dir');
            $process = proc_open($v['script'], $descriptorspec, $pipes, $cwd);
            if (is_resource($process)) {
                fclose($pipes[0]);
                echo $_stdout = stream_get_contents($pipes[1]);
                fclose($pipes[1]);
                $_proc_code = proc_close($process);
                echo "command returned $_proc_code\n";
            }
            $v->cmd_return_code = $_proc_code;
            if (mb_strlen($_stdout,'utf8')>65535){
                $v->stdout_content = substr($_stdout, 0, 32763)."\n------\n".substr($_stdout, -32763);
            }else{
                $v->stdout_content = $_stdout;
            }
            if ($_proc_code == 0){
                $v->status = QueneJob::STATUS_DONE;
            }else{
                $v->status = QueneJob::STATUS_ERROR;
            }
            if (!$v->save()){
                var_dump(Model::getModelError($v));
            }
        }
        \Yii::$app->cache->set($key, QueneJob::STATUS_DONE, 86400*30);
    }

    /**
     * php yii job/backup-by-demi
     * 备份
     * @throws \yii\base\Exception
     */
    public function actionBackupByDemi()
    {
        if (!is_dir(\Yii::getAlias(Env::$demi_backup_folder))){
            FileHelper::createDirectory(\Yii::getAlias(Env::$demi_backup_folder), 0777);
        }
        $backup = \Yii::$app->backup;
        $file = $backup->create();
        $this->stdout('Backup file created: ' . $file . PHP_EOL, \yii\helpers\Console::FG_GREEN);
    }

    /**
     * php yii job/update-area-by-jd
     * 更新地址
     * @throws \yii\db\Exception
     */
    public function actionUpdateAreaByJd($fid = 0, $is_delete = 0)
    {
        $instance = JdArea::instance();
        if ($is_delete)Area::deleteAll();
        $instance->updateLocalDbModel(Area::class, $fid, 1);
    }

    /**
     * 开启swoole websocket 聊天服务器
     * php yii job/wschat-server-start
     */
    public function actionWschatServerStart()
    {
        $conf = Env::getSwooleWebsocketConf();
        $serv = new ChatServer([
            'ip' => $conf['ip'],
            'port' => $conf['port'],
        ]);
        $serv->start();
    }

    /**
     * 开启web-proxy-server
     * php yii job/web-proxy-server-start
     */
    public function actionWebProxyServerStart()
    {
        $serv = new WebProxyServer();
        $serv->run();
    }

    /**
     * 开启proxy-tcp-server
     * php yii job/proxy-tcp-server-start
     */
    public function actionProxyTcpServerStart()
    {
        $serv = new ProxyTcpServer();
        $serv->run();
    }

    /**
     * php yii job/swoole-serv-start
     */
    public function actionSwooleServStart()
    {
        $_s = new Server();
        $_s->start();
    }

    /**
     * php yii job/swoole-client-start
     */
    public function actionSwooleClientStart()
    {
        $_c = new Client();
        $_c->connect();
    }

    /**
     * php yii job/reverse-proxy-serv-start 0.0.0.0 9520
     * @desc 开启反向代理服务器
     * @param $host
     * @param $listen_port
     */
    public function actionReverseProxyServStart($outer_host, $outer_port)
    {
        $_s = new OuterNet();
        $_s->outer_host = $outer_host;
        $_s->outer_port = $outer_port;
        $_s->start();
    }

    /**
     * php yii job/yiichina-sign | php yii_dev job/yiichina-sign
     * @desc https://www.yiichina.com 签到
     * @throws
     */
    public function actionYiichinaSign()
    {
        define('SiteUrl','https://www.yiichina.com/');   //站点URL
        define('LoginUrl',SiteUrl.'login');             //登录页面地址
        define('SignInUrl',SiteUrl.'registration');     //请求签到地址
        define('UserName', Env::$yiichina_login_name);      //账号 自己配置
        define('PassWord', Env::$yiichina_login_password);      //密码 自己配置
        $curl = new Curl();
//请求登录页面
        $curl->get(LoginUrl);
        if ($curl->error) {
            echo '请求登录页面->Error: ' . $curl->errorCode . ': ' . $curl->errorMessage . "\n"; exit;
        }
        $loginHtml  = $curl->response;
        $cookie  = $curl->getResponseCookies();
//解析登录页面
        $doc = \phpQuery::newDocumentHTML($loginHtml);
//获取防止 跨站请求伪造 加密字符串
        $_csrf = $doc->find('input[name=_csrf]')->val();
        /******************************************开始登录********************************************/
//带上Referrer
        $curl->setReferrer(SiteUrl);
//设置  UA
        $curl->setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36');
//带上 请求 头
        $curl->setHeader('X-Requested-With', 'XMLHttpRequest');
//带上 sessionId 的 cookie
        $curl->setCookies($cookie);
        $userInfo = [
            '_csrf'  => $_csrf,
            'LoginForm[username]'  => UserName,
            'LoginForm[password]'  => PassWord,
            'LoginForm[rememberMe]'  => '1',
        ];
        $curl->post(LoginUrl,$userInfo,1);
        if ($curl->error) {
            echo '开始登录->Error: ' . $curl->errorCode . ': ' . $curl->errorMessage . "\n"; exit;
        }
//获取 登录的时产生的 cookie
        $cookie  += $curl->getResponseCookies();
        /******************************************开始签到********************************************/
//带上Referrer
        $curl->setReferrer(SiteUrl);
//设置  UA
        $curl->setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36');
//带上 请求 头
        $curl->setHeader('X-Requested-With', 'XMLHttpRequest');
//带上 sessionId 的 cookie
        $curl->setCookies($cookie);
//签到
        $curl->post(SignInUrl,['_csrf'=>$_csrf]);
        if ($curl->error) {
            echo '开始签到->Error: ' . $curl->errorCode . ': ' . $curl->errorMessage . "\n"; exit;
        }
        $signInResponse  = $curl->response;
//{"status":1,"message":"已连续1天"}
        $responseArray = json_decode($signInResponse,1);
        if($responseArray['status']?:0){
            $msg = date('Y-m-d').' sgin in OK'.PHP_EOL;
        }else{
            $msg = date('Y-m-d').' sgin in Fail:'.($responseArray['message']?:'').PHP_EOL;
        }
        echo $msg;
        \Yii::$app->monolog->getLogger('yiichina_sign')->log('info', $msg);
    }
}